<?php
/**
 * Created by PhpStorm.
 * User: yuliang
 * Date: 2017/6/2
 * Time: 下午12:02
 */

namespace app\webapi\controller;


use app\common\controller\Api;
use app\common\model\Course;
use think\Cache;
use think\Cookie;
use think\Db;
use beecloud\rest;

class Order extends Api
{
    // 我的研币
    public function chargeCenter(){
        $token = input('post.token');
        $uid = input('post.uid');
        $type = input('post.type'); // 1-消费记录，2-充值记录
        $page = input('post.page')?input('post.page'):1;
        $pageSize = 8;
        $validate = $this->validate(['uid'=>$uid,'token'=>$token,'type'=>$type],['uid'=> 'require|number','token'=>'require','type'=>'require|in:1,2']);
        if($validate !== true){
            return api_error('1000',$validate);
        }

        if(isset($uid) && isset($token)){
            $checkToken = $this->checkAuthToken($token);
            if(!$checkToken){
                return api_error('9999','请重新登陆！');
            }
        }

        // 获取用户金额
        $user = model('User')->field('coin')->where(['uid'=>$uid])->find();
        $result['coin'] = $user['coin'];
        $result['card'] = Db::name('card')->field('id,price,coin')->order('price asc')->select();
        $result['data'] = array();
        if($type == 1){
            // 用户消费记录
            $consume = Db::table('jy_course_order')->alias('a')->join('jy_oauth_user b','a.user_id = b.uid')->field('a.*,b.nick_name,b.real_name')->where(['a.user_id'=>$uid,'a.status'=>1])->page($page,$pageSize)->order('create_time desc')->select();
            if(!empty($consume)){
                foreach ($consume as $key=>$value){
                    $consume[$key]['teachers'] = teacher_info($value['teacher_id']);
                    $consume[$key]['name'] = $value['real_name']?$value['real_name']:$value['nick_name'];
                }
                $result['data'] = $consume;
            }
        }else{
            // 用户充值记录
            $chargeRecord = Db::name('pay_records')->where(['user_id'=>$uid,'status'=>2])->page($page,$pageSize)->order('create_time')->select();
            if(!empty($chargeRecord)){
                foreach ($chargeRecord as $key=>$value){
                    $chargeRecord['teachers'] = teacher_info($value['teacher_id']);
                }
            }
            $result['data'] = $chargeRecord;
        }
        return api_return('操作成功！',$result);
    }


    // 用户购买
    public function buyCourse(){
        $token = input('post.token');
        $uid = input('post.uid');
        $course_id = input('post.course_id');
        $validate = $this->validate(['uid'=>$uid,'token'=>$token],['uid'=> 'require|number','token'=>'require']);
        if($validate !== true){
            return api_error('1000',$validate);
        }

        if(isset($uid) && isset($token)){
            $checkToken = $this->checkAuthToken($token);
            if(!$checkToken){
                return api_error('9999','请重新登陆！');
            }
        }
        $user = model('User')->where(['uid'=>$uid,'status'=>1])->find();
        if($user){
            $coin = $user['coin'];
            $course = model('Course')->where(['id'=>$course_id,'status'=>1])->find();
            if($course){
                $price = $course['price'];
                if($course['type'] == 6){
                    // 电子书课程必须填写姓名及邮箱
                    $real_name = input('post.real_name');
                    $email = input('post.email');
                    $validate = $this->validate(['real_name'=>$real_name,'email'=>$email],['real_name'=> 'require','email'=>'require|email']);
                    if($validate !== true){
                        return api_error('1000',$validate);
                    }
                }
            }else{
                return api_error('4002','课程不存在！');
            }
            // 判断用户研币是否充足
            if(($coin - $price) >0){
                $data = [
                    'trade_number' => order_no(2),
                    'user_id' => $uid,
                    'course_id' => $course_id,
                    'course_name' => $course['title'],
                    'teacher_id' => $course['teacher_id'],
//                    'teacher_name' => input('post.teacher_name'),
                    'teacher_name' => $course['teacher_name'],
                    'price' => $course['price'],
                    'pay_price' => $course['price'],
                    'attachment' => $course['attachment'],
                    'user_name' => $user['real_name']?$user['real_name']:$user['nick_name'],
                    'email' => $user['email']
                ];

                // 电子书购买填写邮箱
                if($course['type'] == 6){
                    $data['user_name'] = input('post.real_name');
                    $data['email'] = input('post.email');
                }

                $createOrder = model('CourseOrder')->save($data);
                if($createOrder){
                    // 购买成功，扣除研币
                    $realCoin = $coin - $price;
                    if($course['type'] == 6){
//                        $path = $course['file_url'];
                        $body = mail_content($course['title'],$course['price'],$course['subtitle'],$course['file_url']);
                        send_mail(input('post.email'),'尊敬的用户','海滨课堂',$body);
                        $result = model('User')->save(['coin'=>$realCoin,'real_name'=>input('post.real_name'),'email'=>input('post.email')],['uid'=>$uid]);
                    }else{
                        $result = model('User')->save(['coin'=>$realCoin],['uid'=>$uid]);
                    }

                    if($result){

                        return api_return('购买课程成功！',array());
                    }else{
                        return api_error('4005','扣款失败！');
                    }
                }else{
                    return api_error('4004','对不起，创建订单失败！');
                }
            }else{
                return api_error('4003','对不起，您的研币不足，请充值！');
            }
        }else{
            return api_error('4001','对不起，该用户不存在！');
        }

    }

    // 用户充值
    public function charge(){
        $card_id = input('post.card_id');
        $uid = input('post.uid');
        $token = input('post.token');
        $price = input('post.price');
        $channel_type = input('post.channel_type');

        $validate = $this->validate(['uid'=>$uid,'token'=>$token,'card_id'=>$card_id,'price'=>$price,'channel_type'=>$channel_type],
            ['uid'=> 'require|number','token'=>'require','price'=>'require|number','card_id'=>'require|number','channel_type'=>'require']);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $checkToken = $this->checkAuthToken($token);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }

        // 校验充值卡信息
        $card_info = Db::name('card')->where('id',$card_id)->find();
        if(empty($card_info) || $price != $card_info['price']){
            return api_error('4006','对不起，订单信息有误！');
        }

        // 获取个人信息
        $user = Db::name('oauth_user')->where(['uid'=>$uid,'status'=>1])->find();
        if(empty($user)){
            return api_error('4007','用户不存在或已被禁用！');
        }
        $bill_no = order_no(1);


        $info = [
            'order_number' => $bill_no,
            'pay_title' => '海滨课堂'.$bill_no,
            'pay_channel' => $channel_type,
            'user_id' => $uid,
            'user_name' => $user['real_name']?$user['real_name']:$user['nick_name'],
            'price' => $card_info['price'],
            'coin' => $card_info['coin'],
            'pay_price' => $price,
            'card_id' => $card_id
        ];
        $order_pay = model('PayOrder')->save($info);
        if($order_pay){
            $config = config('beecloud');
            $beecloud = \beecloud\rest\api::registerApp($config['app_id'],$config['app_secret'],$config['master_secret'],$config['test_secret']);
            $total_price = intval($price*100);
            if($channel_type == 'ALI_QRCODE'){
                $data = array(
                    'timestamp' => time() * 1000,
                    'channel' => $channel_type, //渠道类型
                    'title' => '海滨教育-'.$bill_no,   //订单标题
                    'bill_no' => $bill_no,    //订单编号
                    'total_fee' => $total_price, //订单金额(int 类型) ,单位分
                    'qr_pay_mode' => "",
                    'return_url' => 'http://ke.haibinjiaoyu.com/ucenter/cb', //渠道类型:ALI_WEB、ALI_QRCODE、UN_WEB、JD_WAP、JD_WEB时为必填
                    'bill_timeout' => 360, //京东(JD*)不支持该参数
                );
            }else if($channel_type == 'WX_NATIVE'){
                $data = array(
                    'timestamp' => time() * 1000,
                    'channel' => 'WX_NATIVE', //渠道类型
                    'title' => '海滨教育-'.$bill_no,   //订单标题
                    'bill_no' => $bill_no,    //订单编号
                    'total_fee' => $total_price //订单金额(int 类型) ,单位分
                );
            }else{
                return api_error('1000','消费渠道有误！');
            }
            try {
                $result = \beecloud\rest\api::bill($data);

                if($channel_type == 'ALI_QRCODE'){
                    if(isset($result->url)){
                        $code_url = $result->url;
//                        header("Location:$result->url");
                    }else if(isset($result->html)) {
//                        echo $result->html;
                        $code_url = $result->html;
                    }
                }else{
                    if ($result->result_code != 0) {
//                        print_r($result);
                        exit();
                    }
                    $code_url = $result->code_url;
//                    return api_return('操作成功！',array('code_url'=>$code_url));
                }
                return api_return('操作成功！',array('code_url'=>$code_url,'order_no'=>$bill_no));
            } catch (\Exception $e) {
                return api_error('4009',$e->getMessage());
            }
        }else{
            return api_error('4008','对不起，创建订单失败！');
        }
    }

    public function webhook(){
        $config = config('beecloud');
        $appId = $config['app_id'];
        $masterSecret = $config['master_secret'];

        $jsonStr = file_get_contents("php://input");
        $msg = json_decode($jsonStr);
        Cache::set('msg',$msg);
//        $msg = Cache::get('msg');
        $sign = md5($appId . $msg->transaction_id . $msg->transaction_type . $msg->channel_type . $msg->transaction_fee.$masterSecret);
        if ($sign != $msg->signature) {
            // 签名不正确
            exit();
        }
        $model = model('PayOrder');

        // 订单过滤去重
        if($msg->transaction_type == 'PAY'){
            $order = $model->where('order_number',$msg->transaction_id)->where('status',2)->find();
            if($order){
                exit();
            }
        }elseif ($msg->transaction_type == 'REFUND'){
            $order = $model->where('order_number',$msg->transaction_id)->where('status',3)->find();
            if($order){
                exit();
            }
        }

        // 金额校验
        $order = $model->where('order_number',$msg->transaction_id)->find();
        $price = $order['pay_price']*100;
        if($price != $msg->transaction_fee){
            exit();
        }

        // 处理业务逻辑和返回
        if($msg->transaction_type == "PAY") {

            //支付状态是否变为支付成功,true代表成功
            $status = $msg->trade_success;

            if($status !== true){
                exit();
            }
            //message_detail 参考文档
            //channel_type 微信/支付宝/银联/快钱/京东/百度/易宝/PAYPAL/BC
            switch ($msg->channel_type) {
                case "WX":
                    $out_trade_no = $msg->message_detail->out_trade_no;
                    break;
                default :
                    $out_trade_no = '';
            }
            $data = [
                'status' => 2,
                'trade_number' => $out_trade_no,
                'pay_time' => date('Y-m-d H:i:s',time())
            ];
            $updateOrder = $model->save($data,['order_number'=>$msg->transaction_id]);
            Db::name('oauth_user')->where('uid',$order['user_id'])->update([
                'coin' => ['exp','coin+'.$order['coin']]
            ]);
        }else if ($msg->transaction_type == "REFUND") { //退款的结果

        }
        echo 'success';
    }

    // return_url 查询是否支付成功
    public function checkBuy(){
        $where['order_number'] = input('post.order_no');
        $where['user_id'] = input('post.uid');
        $rule = [
            'order_number' => 'require|number|length:20',
            'user_id' => 'require|number',
        ];
        $validate = $this->validate($where,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 检验订单有效性
        $result = Db::name('pay_records')->where($where)->select();
        if(empty($result)){
            return api_error('4011','无效的订单！');
        }

        $out_time = 10;
        set_time_limit(0);

        $i = 0;
        while(true) {
            usleep(300000);
            $i++;

            // 获得数据
            $where['status'] = 2;
            $res = Db::name('pay_records')->where($where)->select();
            //
            if ($res) {
                return api_return('支付成功！', array());
                break;
            }
            // 服务器($_POST['time'] * 0.5)秒后告诉客服端无数据
            if ($i >= $out_time) {
                return api_error('4010', '未支付成功！');
                break;
            }
        }
        return '';
    }

    public function tool(){

        $dir = './uploads/20170705/6bdeaa2c13003021d3186fe20467ba00.jpg';
        $result = send_mail('335010991@qq.com','尊敬的用户','海滨课堂邮件','这是您购买的课程！',$dir);
    }

}